package models

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"strconv"
)

type ResourceElb struct {
	// 阿里云 nlb D:\nyy_work\go_path\pkg\mod\github.com\aliyun\alibaba-cloud-sdk-go@v1.62.559\services\nlb\struct_loadbalancer_info.go
	// 阿里云 alb D:\nyy_work\go_path\pkg\mod\github.com\aliyun\alibaba-cloud-sdk-go@v1.62.559\services\alb\struct_load_balancer.go

	Model // 不用每次写ID 和 createAt了
	ResourceCommon

	// 重点字段
	LoadBalancerType   string `json:"LoadBalancerType" gorm:"comment:类型有 nlb alb clb"`
	BandwidthCapacity  int    `json:"BandwidthCapacity" gorm:"comment:带宽包上限 50Mb 100Mb"`
	AddressType        string `json:"AddressType" gorm:"comment:公网类型还是内网类型"`
	DNSName            string `json:"DNSName" gorm:"comment: dns解析地址"`
	BandwidthPackageId string `json:"BandwidthPackageId" gorm:"comment:绑定的带宽包"`
	CrossZoneEnabled   bool   `json:"CrossZoneEnabled" `

	BindNodes []*StreeNode `json:"bind_nodes" gorm:"many2many:bind_elbs;"` // 多对多
}

// 这里要写上 会变的字段
func (rh *ResourceElb) GenHash() string {
	h := md5.New()
	h.Write([]byte(rh.InstanceId))
	h.Write([]byte(rh.LoadBalancerType))
	h.Write([]byte(rh.DNSName))
	h.Write([]byte(strconv.Itoa(rh.BandwidthCapacity)))
	return hex.EncodeToString(h.Sum(nil))
}

func (obj *ResourceElb) Create() error {
	return Db.Create(obj).Error

}
func (obj *ResourceElb) DeleteOne() error {

	return Db.Select(clause.Associations).Unscoped().Delete(obj).Error

}

func DeleteResourceElbOneByInstanceId(iid string) error {

	return Db.Select(clause.Associations).Unscoped().Where("instance_id = ?", iid).Delete(&ResourceElb{}).Error
}

func (obj *ResourceElb) CreateOne() error {
	return Db.Create(obj).Error

}

func (obj *ResourceElb) UpdateOne() error {
	return Db.Where("id = ?", obj.ID).Updates(obj).Error

}

func (obj *ResourceElb) UpdateBindNodes(nodes []*StreeNode) error {

	return Db.Model(obj).Association("BindNodes").Replace(nodes)

}

func GetResourceElbAll() (objs []*ResourceElb, err error) {
	err = Db.Preload("BindNodes").Find(&objs).Error
	return
}

func GetResourceElbByLevel(level int) (objs []*ResourceElb, err error) {
	err = Db.Where("level = ?", level).Preload("OpsAdmins").Find(&objs).Error
	return
}

// select * from ecs where
func GetResourceElbByIdsWithLimitOffset(ids []int, limit, offset int) (objs []*ResourceElb, err error) {
	err = Db.Limit(limit).Offset(offset).Find(&objs, ids).Error
	return
}

func GetResourceElbByInstanceId(instanceId string) (*ResourceElb, error) {

	var dbObj ResourceElb
	//err := Db.Where("username = ?", userName).Preload("Roles").Joins("Menus").First(&dbUser).Error
	err := Db.Where("instance_id = ?", instanceId).Preload("BindNodes").First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("ResourceElb不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}

func GetResourceElbById(id int) (*ResourceElb, error) {

	var dbObj ResourceElb
	//err := Db.Where("username = ?", userName).Preload("Roles").Joins("Menus").First(&dbUser).Error
	err := Db.Where("id = ?", id).Preload("BindNodes").First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("ResourceElb不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}

func GetResourceElbUidAndHash() (map[string]string, error) {

	var objs []*ResourceElb

	err := Db.Find(&objs).Error
	if err != nil {
		return nil, err
	}

	m := make(map[string]string)
	for _, h := range objs {
		m[h.InstanceId] = h.Hash
	}
	return m, nil
}
